package java_test;

import java.util.Arrays;

public class ArrayInsertElm {
    public static void main(String[] args) {
        int array[] = {2, 5, -2, 6, -3, 8, 0, -7, -9, 4};
        Arrays.sort(array);
        int index = Arrays.binarySearch(array, 3);
        System.out.println("元素 1 所在位置（负数为不存在）：" + index);
        int newIndex = -index - 1;
        array = insertElement(array, 1, newIndex);
        printArray("数组添加元素 1", array);
    }

    private static void printArray(String message, int array[]) {
        System.out.println(message + ": [length: " + array.length + "]");
        for (int i = 0; i < array.length; i++) {
            if (i != 0) {
                System.out.print(", ");
            }
            System.out.print(array[i]);
        }
        System.out.println();
    }

    private static int[] insertElement(int[] array, int i, int newIndex) {
        int length = array.length;
        int destination[] = new int[length - 1];
        System.arraycopy(array, 0, destination, 0, newIndex);
        destination[i] = i;
        System.arraycopy(array, 0, destination, 0, newIndex - 1);
        return destination;
    }
}
